<template>
  <div id="app">
    <el-card shadow="always">
      <el-form :inline="true" size="medium" :model="studentSearch" class="demo-form-inline">
        <el-form-item >
          <el-input v-model="studentSearch.sname" placeholder="学生姓名" clearable></el-input>
        </el-form-item>
        <el-form-item >
          <el-input v-model="studentSearch.addr" placeholder="学生住址" clearable></el-input>
        </el-form-item>
        <el-form-item >
          <el-select v-model="studentSearch.cid" placeholder="所在班级">
            <el-option label="所有班级" value="0"></el-option>
            <el-option :label="c.cname" :value="c.cid" v-for="c in classesList" :key="c.cid"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search" icon="el-icon-user">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="addStudent" icon="el-icon-plus">添加学生</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" icon="el-icon-remove" plain @click="Deletestudent">批量删除</el-button>
        </el-form-item>
      </el-form>

      <el-table
          :data="studentList"
          style="width: 100%"
          @selection-change="SelectionStudents">
        <el-table-column
            type="selection">
        </el-table-column>
        <el-table-column
            label="学号"
            prop="sid"
            align="center"
            width="180">
        </el-table-column>
        <el-table-column
            label="姓名"
            align="center"
            prop="sname">
        </el-table-column>
        <el-table-column
            label="性别"
            align="center"
            prop="sex">
        </el-table-column>
        <el-table-column
            label="年龄"
            align="center"
            prop="age">
        </el-table-column>
        <el-table-column
            label="住址"
            align="center"
            prop="addr">
        </el-table-column>
        <el-table-column
            label="所在班级"
            align="center"
            prop="cname">
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
                size="mini"
                @click="editStudent(scope.row)">编辑</el-button>
            <el-button
                size="mini"
                type="danger"
                @click="Deletestudent(scope.$index,scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[2, 4, 6, 8]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>

    </el-card>

    <el-card>
      <el-table
          :data="classesList"
          style="width: 100%">
        <el-table-column
            label="班级编号"
            prop="cid"
            align="center"
            width="180">
        </el-table-column>
        <el-table-column
            label="班级名称"
            align="center"
            prop="cname">
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
                size="mini"
                @click="">编辑</el-button>
            <el-button
                size="mini"
                type="danger"
                @click="">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="dialogFormVisible">
      <el-form :model="studentedit" :rules="editStuRules" ref="ruleForm">
        <el-form-item label="学生姓名" prop="sname" :label-width="formLabelWidth" >
          <el-input v-model="studentedit.sname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="学生性别" prop="sex" :label-width="formLabelWidth" >
          <el-radio v-model="studentedit.sex" label="男">男</el-radio>
          <el-radio v-model="studentedit.sex" label="女">女</el-radio>
        </el-form-item>
        <el-form-item label="学生年龄" prop="age" :label-width="formLabelWidth" >
          <el-input v-model.number="studentedit.age" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="学生住址" prop="addr" :label-width="formLabelWidth" >
          <el-input v-model="studentedit.addr" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="学生班级" prop="cid" :label-width="formLabelWidth" style="width: 1200px" >
          <el-select v-model="studentedit.cid" placeholder="请选择学生班级" >
            <el-option :label="c.cname" :value="c.cid" v-for="c in classesList" :key="c.cid"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveStudent()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import studentApi from "@/api/student"
import classesApi from "@/api/classes"
export default {
  data() {
    let checkAge = (rule, value, callback) => {
      if (value === '' || value == null) {
        return callback(new Error('年龄不能为空'))
      } else if (!Number.isInteger(value)) {
        return callback(new Error('年龄必须为数字值'))
      } else if (value < 1 || value > 200) {
        return callback(new Error('年龄必须在1-200之间'))
      } else {
        callback()
      }
    }

    return {
      studentList: [],
      page: 1,
      pageSize: 2,
      total: 100,
      studentSearch: {},
      classesList: [],
      dialogFormVisible: false,
      formLabelWidth: '150px',
      studentedit: {},
      STUselect:[],
      deletesid:[],
      title: '编辑学生',
      addoredit:0,

      editStuRules: {
        sname: [
          {required: true, message: '请输入学生姓名', trigger: 'blur'},
        ],
        sex: [
          {required: true, message: '请选择性别', trigger: 'blur'},
        ],
        age: [
          { validator : checkAge, trigger: 'blur'}
        ],
        addr: [
          {required: true, message: '请输入学生住址', trigger: 'blur'},
        ],
        cid: [
          {required: true, message: '请选择学生班级', trigger: 'blur'},
        ]
      }

    }
  },
  created() {
    // this.findbypage()
    this.findClasses()
    this.searchSTU()
  },

  methods: {

    saveStudent() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (this.addoredit === 0) {
            const {data: res} = await studentApi.addSTU(this.studentedit)
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: res.message,
                duration: 1000,
                onClose: () => {
                  this.dialogFormVisible = false
                  this.search()
                }
              })
            } else {
              this.$message({
                type: 'error',
                message: res.message,
              })
            }
          } else {
            const {data: res} = await studentApi.updateSTU(this.studentedit)
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: res.message,
                duration: 1000,
                onClose: () => {
                  this.dialogFormVisible = false
                  this.search()
                }
              })
            } else {
              this.$message({
                type: 'error',
                message: res.message,
                duration: 1000,
              })
            }
          }
        } else {
          console.log('提交失败');
          return false;
        }
      });
    },

    SelectionStudents(val) {
      this.STUselect = val;
    },

    async findALLSTU() {
      const {data: res} = await studentApi.findALLSTU()
      if (res.code === 200) {
        this.studentList = res.data.students
      }
    },

    async findClasses() {
      const {data: res} = await classesApi.findClasses()
      if (res.code === 200) {
        this.classesList = res.data.classes
      }
    },

    async findbypage() {
      const {data: res} = await studentApi.findbypage(this.page, this.pageSize)
      if (res.code === 200) {
        this.studentList = res.data.res.rows
        this.total = res.data.res.total
      }
    },

    async searchSTU() {
      const {data: res} = await studentApi.searchSTU(this.page, this.pageSize, this.studentSearch)
      if (res.code === 200) {
        this.studentList = res.data.res.rows
        this.total = res.data.res.total
      }
    },

    async search() {
      const {data: res} = await studentApi.search(1, this.pageSize, this.studentSearch)
      if (res.code === 200) {
        this.studentList = res.data.res.rows
        this.total = res.data.res.total
        this.page = 1
      }
    },

    addStudent() {
      this.dialogFormVisible = true
      this.studentedit = {}
      this.addoredit = 0
      this.title = "添加学生"
    },

    editStudent(row) {
      this.dialogFormVisible = true
      this.addoredit = 1
      this.studentedit = row
      this.title = "编辑学生信息"
    },


    Deletestudent(index,row) {
      this.deletesid = []
      if (row) {
        this.deletesid.push(row.sid)
      } else {
        this.deletesid = this.STUselect.map(m => m.sid)
      }
      if(this.deletesid.length > 0 ) {
        this.$confirm(`是否真的要删除学号为${this.deletesid}的学生吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let this2 = this
          studentApi.deletes(this.deletesid)
              .then(({data: res}) => {
                if (res.code === 200) {
                  this.$message({
                    type: 'success',
                    message: res.message,
                    duration: 1000,
                    onClose: () => {
                      this2.search()
                    }
                  })
                } else {
                  this.$message({
                    type: 'error',
                    message: res.message
                  })
                }
              })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
            duration: 1000,
          });
        });
      }else{
        this.$message({
          type: 'info',
          message: '请至少选择一个要删除的学生',
          duration: 2000,
        })
      }
    },

    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
        this.searchSTU()
    },

    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page = val;
      this.searchSTU()
    }
  }
}
</script>

<style>
.el-card{
  width: 90%;
  margin: 0 auto;
  margin-bottom: 100px;
}
.el-pagination{
  text-align: right;
  margin-top: 15px;
}
</style>